const COS = require('ali-oss');
const secretId = "LTAI5tGDHftHtJ9FEhxjRYmh"
const secretKey = "YQ2i3Lio5JfoHPWkLNTt3epXQ8F3v4"
const regionName = "oss-cn-hangzhou"
const bucketName = "btm-group"
const fs = require('fs')

const cos = new COS({
    // yourregion填写Bucket所在地域。以华东1（杭州）为例，Region填写为oss-cn-hangzhou。
    region: regionName,
    // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
    accessKeyId: secretId,
    accessKeySecret: secretKey,
    // yourbucketname填写存储空间名称。
    bucket: bucketName
})


const cosPrivate = new COS({
    // yourregion填写Bucket所在地域。以华东1（杭州）为例，Region填写为oss-cn-hangzhou。
    region: regionName,
    // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
    accessKeyId: secretId,
    accessKeySecret: secretKey,
    // yourbucketname填写存储空间名称。
    bucket: 'btm-group-private',
    timeout:1000*60*10,
    secure:true
})

const rootDir = 'resources/'

function uploadFile(filepath, filename,mime) {
    async function put() {
        try {
            let options = {
                'mime':mime
            };
            let result = await cos.put(rootDir + filename, filepath,options);
            console.log(result);
            return result.url
        } catch (e) {
            console.log(e);
        }
    }
    return put()
}

async function isExistObject(name, options = {}) {
    let result = false
    try {
        await cos.head(rootDir + name, options);
        result = true
    } catch (error) {
        if (error.code === 'NoSuchKey') {
            result = false
        }
    }
    return result
}

async function uploadPrivateFile(filepath, filename,mime) {
    try {
        let options = {
            'mime':mime
        };
        //var file = dataURLtoFile(Base64Util.base64Sync(filepath), filename);
        let result = await cosPrivate.put(rootDir + filename, filepath,options);
        console.log(result);
        return result.url
    } catch (e) {
        console.error('oss uploadPrivateFile error:',e.message);
        return null;
    }
}

async function signatureUrl(key){
    let signUrl = cosPrivate.signatureUrl(key, {expires: 60, method: 'GET'});
    console.log('signUrl===',signUrl)
    return signUrl;
}

module.exports = {
    uploadFile,
    uploadPrivateFile,
    signatureUrl,
    isExistObject,
}